import api from '../api';
import { sleep } from '@/utils/common';
import { Loading } from 'element-ui';
const mixin = {
  data() {
    return {
    };
  },
  methods: {
    go(path) {
      console.log('here we go ', path);
      this.$router.push(path);
    },
    goNewTab(path) {
      console.log('here we goNewTab ', path);
      window.open(window.location.origin + '/#' + path, '_blank');
    },
    goParam(param) {
      return this.$route.query[param];
    },
    goBack() {
      this.$router.go(-1);
    },
    sleep,
    $$confirm({ type = 'info', text = '', title = '提示', btnConfirm = '确认', btnCancel = '取消' }) {
      return this.$confirm(text, title, {
        confirmButtonText: btnConfirm,
        cancelButtonText: btnCancel,
        type: type,
        offset: 300
      });
    },
    $$alert({ text = '', title = '提示', btnConfirm = '确认' }) {
      return this.$alert(text, title, {
        confirmButtonText: btnConfirm
      });
    },
    $$loading(val = '加载中') {
      this.loadingInstance = Loading.service({
        text: val,
        background: 'rgba(255,255,255,.6)'
      });
    },
    $$loadingClose() {
      this.$$loading();
      this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        this.loadingInstance.close();
      });
    },
    $$warning(message) {
      this.$$loadingClose();
      this.$message({
        showClose: true,
        message,
        type: 'warning',
        offset: 300
      });
    },
    $toast(val) {
      this.$$warning(val);
    },
    $post: api.post,
    $get: api.get,
    $put: api.put,
    $del: api.del,
    $$error(message) {
      this.$$loadingClose();
      this.$message({
        showClose: true,
        message,
        type: 'error',
        offset: 300
      });
    },
    optionsFilter(arr = []) {
      if (!arr.length) return;
      if (typeof arr[0] !== 'string') {
        const finArr = [];
        for (const i in arr) {
          finArr.push(arr[i].value);
        }
        arr = finArr;
      }
      let str = '';
      arr.forEach(ele => str += `-${ele}`);
      str = str.slice(1);
      return str;
    },
    $$success(message) {
      this.$$loadingClose();
      this.$message({
        showClose: true,
        message,
        type: 'success',
        offset: 300
      });
    },
    jump(val) {
      window.location.href = val;
    },
    jumpNewTab(val) {
      window.open(location.origin + '/#' + val, '_blank');
    },
  },
  filters: {
    formatMoney: function(value = 0, len = 2) {
      return value ? value.toFixed(len) : value;
    },
    formatFixed2: function(value = 0) {
      return Math.round(value * 100) / 100;
    },
    formatFloor: function(value = 0) {
      const reg = /^-?\d+$/;
      if (reg.test(value)) return value;
      const s = JSON.stringify(value);
      return s.substring(0, s.indexOf(`.`) + 3);
    }
  }
};

export default mixin;
